package com.ruoyi.project.beautyflower;

import ai.advance.cmp.api.client.CMPAsyncClient;
import ai.advance.cmp.api.client.CMPSyncClient;
import ai.advance.cmp.api.client.bean.ResponseBean;
import ai.advance.cmp.api.client.bean.dto.*;
import ai.advance.cmp.api.client.bean.dto.query.*;
import ai.advance.cmp.api.client.bean.dto.response.BindCardAuthRequestResponseDTO;
import ai.advance.cmp.api.client.enums.ContractStatus;
import ai.advance.cmp.api.client.enums.Gender;
import ai.advance.cmp.api.client.enums.GuarantyType;
import ai.advance.cmp.api.client.enums.IdType;
import ai.advance.cmp.api.client.enums.RateType;
import ai.advance.cmp.api.client.enums.RepaymentMethod;
import ai.advance.cmp.api.client.enums.TenorUnit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.app.util.CalculationUtil;
import com.ruoyi.project.app.util.GenerateNum;
import com.ruoyi.project.app.util.OrderCoderUtil;
import com.ruoyi.project.app.util.XException;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BfUtil {
    private static final Logger log = LoggerFactory.getLogger(BfUtil.class);

//    private static CMPSyncClient apiSyncClient = new CMPSyncClient("https://staging-api-cmp.advai.cn", "TIANMEIHUA", "8oQXDH4P3no4oviK");
//    private static CMPAsyncClient apiAsyncClient = CMPAsyncClient.getInstance("https://staging-api-cmp.advai.cn", "JUMEI", "8oQXDH4P3no4oviK");

    /**
     * 正式环境
     */
    private static CMPSyncClient apiSyncClient = new CMPSyncClient("https://production-api-cmp.ndmicro.com", "n0PIGcP3YnampVk7iv0wZI0Nskdi8Q", "JxlEykEk7JzKwbkVzRFeooQQcp3DPJrVAoKoIhlB");
    private static CMPAsyncClient apiAsyncClient = CMPAsyncClient.getInstance("https://production-api-cmp.ndmicro.com", "TIANMEIHUA", "8oQXDH4P3no4oviK");
    private static String TRAFFIC = "TIANMEIHUA";
    private static String PRODUCT = "TIANMEIHUA_CASHLOAN";


    private static String USER_ID = "980400" + (new Random()).nextInt(10000000);
    private static String ID_NUMBER;
    private static String MOBILE_NUMBER;

    public BfUtil() {
    }

    /**
     * 保存还款计划信息（不用调用此接口了）
     * @return
     */
    public static ResponseBean createRepaymentSchedule(RepaymentScheduleCreateDTO scsd) {
        RepaymentScheduleCreateDTO repaymentScheduleCreateDTO = new RepaymentScheduleCreateDTO();
        repaymentScheduleCreateDTO.setTrafficIdentifier(TRAFFIC);
        repaymentScheduleCreateDTO.setProductIdentifier(PRODUCT);
        USER_ID=scsd.getUserId();
        repaymentScheduleCreateDTO.setUserId(USER_ID);
        repaymentScheduleCreateDTO.setOrderId(genOrderId());
        repaymentScheduleCreateDTO.setInstallments(scsd.getInstallments());
        repaymentScheduleCreateDTO.setLoanDate(DateUtils.getDate());
        repaymentScheduleCreateDTO.setDetails(constructRepaymentScheduleDetails());
        return apiSyncClient.createRepaymentSchedule(repaymentScheduleCreateDTO);
    }

    /**
     * 更换订单还款银行卡
     * @return
     */
    public static ResponseBean replaceRepaymentBankCardDemo(OrderReplaceRepaymentBankCardDTO offbcd) {
        OrderReplaceRepaymentBankCardDTO replaceRepaymentBankCardDTO = new OrderReplaceRepaymentBankCardDTO();
        replaceRepaymentBankCardDTO.setTrafficIdentifier(TRAFFIC);
        replaceRepaymentBankCardDTO.setProductIdentifier(PRODUCT);
        USER_ID=offbcd.getUserId();
        replaceRepaymentBankCardDTO.setUserId(USER_ID);
        replaceRepaymentBankCardDTO.setRepaymentBankAccountName(offbcd.getRepaymentBankAccountName());
        replaceRepaymentBankCardDTO.setRepaymentBankCardNumber(offbcd.getRepaymentBankCardNumber());
        replaceRepaymentBankCardDTO.setRepaymentBankMobileNumber(offbcd.getRepaymentBankMobileNumber());
        replaceRepaymentBankCardDTO.setRepaymentBankName(offbcd.getRepaymentBankName());
        List<String> orderIdList = new ArrayList();//查询该用户的所有订单的订单号集合
        orderIdList.add("123456");
        orderIdList.add("223456");
        replaceRepaymentBankCardDTO.setOrderIdList(orderIdList);
        return apiSyncClient.replaceRepaymentBankCard(replaceRepaymentBankCardDTO);
    }

    /**
     * 提前还款（不用调用此接口了 ）
     * @param pcd
     * @return
     */
    public static ResponseBean createPrepayment(PrepaymentCreateDTO pcd) {
        PrepaymentCreateDTO createDTO = new PrepaymentCreateDTO();
        createDTO.setTrafficIdentifier(TRAFFIC);
        createDTO.setProductIdentifier(PRODUCT);
        USER_ID=pcd.getUserId();
        createDTO.setUserId(USER_ID);
        createDTO.setOrderId(genOrderId());
        createDTO.setPrepaymentActionId(pcd.getPrepaymentActionId());
        createDTO.setPrepaymentDate(DateFormatUtils.format(new Date(), "yyyyMMdd"));
        createDTO.setInstallments(pcd.getInstallments());
        createDTO.setDefaultFine(pcd.getDefaultFine());
        createDTO.setBankAccountName(pcd.getBankAccountName());
        createDTO.setBankCardNumber(pcd.getBankCardNumber());
        createDTO.setBankName(pcd.getBankName());
        createDTO.setBankMobileNumber(pcd.getBankMobileNumber());
        BigDecimal prepaymentAmount = BigDecimal.valueOf(0L);
        List<PrepaymentDetailDTO> prepaymentDetailDTOList = new ArrayList();

        for(int i = 3; i < 9; ++i) {
            PrepaymentDetailDTO prepaymentDetailDTO = new PrepaymentDetailDTO();
            prepaymentDetailDTO.setInstallmentNo(i);
            prepaymentDetailDTO.setDuePrincipalAmount(BigDecimal.valueOf(100L));
            prepaymentDetailDTO.setDueInterestAmount(BigDecimal.valueOf(20L));
            prepaymentDetailDTO.setRepaymentPrincipalAmount(BigDecimal.valueOf(100L));
            BigDecimal repaymentInterestAmount = BigDecimal.valueOf(20L);
            String remark = null;
            if (i % 3 == 0) {
                repaymentInterestAmount = BigDecimal.valueOf(0L);
                remark = "提前还款免息";
            }

            prepaymentDetailDTO.setRepaymentInterestAmount(repaymentInterestAmount);//实际还款利息
            prepaymentDetailDTO.setRemark(remark);
            prepaymentAmount = prepaymentAmount.add(prepaymentDetailDTO.getRepaymentPrincipalAmount().add(prepaymentDetailDTO.getRepaymentInterestAmount()));
            prepaymentDetailDTOList.add(prepaymentDetailDTO);
        }

        if (createDTO.getDefaultFine() == null) {
            createDTO.setDefaultFine(BigDecimal.valueOf(0L));
        }

        createDTO.setPrepaymentAmount(prepaymentAmount.add(createDTO.getDefaultFine()));
        createDTO.setDetails(prepaymentDetailDTOList);
        return apiSyncClient.createPrepayment(createDTO);
    }


    /**
     * 通知还款
     * @param map
     * @return
     */
    public static ResponseBean createNotifyRepayment(Map<String,Object> map) {
        NotifyRepaymentCreateDTO createDTO = new NotifyRepaymentCreateDTO();
        SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyyMMdd");
        String dateFormat = ymdFormat.format(new Date());
        // 计算还款金额
        String money = "0";
        createDTO.setTrafficIdentifier(TRAFFIC);
        createDTO.setProductIdentifier(PRODUCT);
        createDTO.setUserId(map.get("userId")+"");//用户id
        createDTO.setRepaymentActionId(map.get("actionId")+"");//还款流水号
        createDTO.setRepaymentDate(DateFormatUtils.format(new Date(), "yyyyMMdd"));//还款时间
        createDTO.setInstallments(Integer.parseInt(map.get("installments")+""));//还款总期数
        createDTO.setDefaultFine(BigDecimal.valueOf(0L));//还款违约金
        createDTO.setBankAccountName(map.get("bankAccountName")+"");//银行账户名
        createDTO.setBankCardNumber(map.get("bankCardNumber")+"");//银行卡号
        createDTO.setBankName(map.get("bankName")+"");//银行名称
        createDTO.setBankMobileNumber(map.get("bankMobileNumber")+"");//银行卡绑定的手机号
        BigDecimal repaymentAmount =new BigDecimal(map.get("repaymentAmount")+"");//还款金额
        money=repaymentAmount+"";
//                BigDecimal.valueOf(Double.valueOf(map.get("repaymentAmount")+""));
        JSONArray jsonArray = JSON.parseArray(map.get("details")+"");
        List<NotifyRepaymentDetailDTO> notifyRepaymentDetailDTOList = new ArrayList();//提前还款详细
        int count=0;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray jsonArray1=jsonArray.getJSONArray(i);
            for (int i1 = 0; i1 < jsonArray1.size(); i1++) {
                String overdueFee = "0";
                String nowPayTime = dateFormat;//当前时间
                JSONObject jsonObject = (JSONObject) jsonArray1.get(i1);
                //当该计划没有逾期是count进行+1
                if (Integer.valueOf(jsonObject.getString("dueDate"))>=Integer.valueOf(nowPayTime)) {
                    count++;
                }
                NotifyRepaymentDetailDTO notifyRepaymentDetailDTO = new NotifyRepaymentDetailDTO();
                notifyRepaymentDetailDTO.setOrderId(jsonObject.getString("orderId")+"");//订单id
                notifyRepaymentDetailDTO.setInstallmentNo(Integer.parseInt(jsonObject.getString("installmentNo")+""));//还款分期号
                notifyRepaymentDetailDTO.setDuePrincipalAmount(jsonObject.getBigDecimal("duePrincipalAmount"));//应还款本金
                notifyRepaymentDetailDTO.setDueInterestAmount(jsonObject.getBigDecimal("repaymentInterestAmount"));//应还款利息
                if (Integer.valueOf(jsonObject.getString("dueDate"))>=Integer.valueOf(nowPayTime)) {
                    notifyRepaymentDetailDTO.setDefaultedInterestAmount(BigDecimal.valueOf(0D));//应还罚息
                    notifyRepaymentDetailDTO.setRepaymentDefaultedInterestAmount(BigDecimal.valueOf(0D));//实际还款罚息
                }else{
                    try {
                        int days = CalculationUtil.differentDays(ymdFormat.parse(nowPayTime), ymdFormat.parse(jsonObject.getString("dueDate")));
                        overdueFee= CalculationUtil.handleSubStr(overdueFee, CalculationUtil.handleMulStr(String.valueOf(Double.valueOf(jsonObject.getBigDecimal("duePrincipalAmount")+"")*0.001), String.valueOf(days), 2), 2);
                        money = CalculationUtil.handleAddStr(money,overdueFee, 2);//总金额加上当期逾期的利息
                        notifyRepaymentDetailDTO.setDefaultedInterestAmount(new BigDecimal(overdueFee));//应还罚息
                        notifyRepaymentDetailDTO.setRepaymentDefaultedInterestAmount(new BigDecimal(overdueFee));//实际还款罚息
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                notifyRepaymentDetailDTO.setRepaymentPrincipalAmount(jsonObject.getBigDecimal("duePrincipalAmount"));//实际还款本金
                BigDecimal repaymentInterestAmount = jsonObject.getBigDecimal("repaymentInterestAmount");//实际还款利息
                String remark = null;
                if(count>3){
                    if (Integer.valueOf(jsonObject.getString("dueDate"))>=Integer.valueOf(nowPayTime)) {
                        notifyRepaymentDetailDTO.setRepaymentInterestAmount(BigDecimal.valueOf(0D));//实际还款利息
                        money = CalculationUtil.handleSubStr(money,repaymentInterestAmount+"", 2);//总金额减去当期的还款利息
                        remark = "提前还款减息";
                    }else{
                        notifyRepaymentDetailDTO.setRepaymentInterestAmount(repaymentInterestAmount);//实际还款利息
                    }
                }else{
                    notifyRepaymentDetailDTO.setRepaymentInterestAmount(repaymentInterestAmount);//实际还款利息
                }
                notifyRepaymentDetailDTO.setRemark(remark);//备注，如利息减免等有用的信息

                notifyRepaymentDetailDTOList.add(notifyRepaymentDetailDTO);
            }
        }
//        for (int i = 0; i < jsonArray.size(); i++) {
//            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
//            NotifyRepaymentDetailDTO notifyRepaymentDetailDTO = new NotifyRepaymentDetailDTO();
//            notifyRepaymentDetailDTO.setOrderId(jsonObject.getString("orderId")+"");//订单id
//            notifyRepaymentDetailDTO.setInstallmentNo(Integer.parseInt(jsonObject.getString("installmentNo")+""));//还款分期号
//            notifyRepaymentDetailDTO.setDuePrincipalAmount(jsonObject.getBigDecimal("duePrincipalAmount"));//应还款本金
//            notifyRepaymentDetailDTO.setDueInterestAmount(jsonObject.getBigDecimal("repaymentInterestAmount"));//应还款利息
//            notifyRepaymentDetailDTO.setDefaultedInterestAmount(BigDecimal.valueOf(0D));//应还罚息
//            notifyRepaymentDetailDTO.setRepaymentPrincipalAmount(jsonObject.getBigDecimal("duePrincipalAmount"));//实际还款本金
//            BigDecimal repaymentInterestAmount = jsonObject.getBigDecimal("repaymentInterestAmount");//实际还款利息
//            String remark = null;
////            if (i % 3 == 0) {
////                repaymentInterestAmount = BigDecimal.valueOf(0L);
////                remark = "提前还款减息";
////            }
//
//            notifyRepaymentDetailDTO.setRepaymentInterestAmount(repaymentInterestAmount);//实际还款利息
//            notifyRepaymentDetailDTO.setRepaymentDefaultedInterestAmount(BigDecimal.valueOf(0D));//实际还款罚息
//            notifyRepaymentDetailDTO.setRemark(remark);//备注，如利息减免等有用的信息
//
////            repaymentAmount = repaymentAmount.add(notifyRepaymentDetailDTO.getRepaymentPrincipalAmount().add(notifyRepaymentDetailDTO.getRepaymentInterestAmount()).add(notifyRepaymentDetailDTO.getRepaymentDefaultedInterestAmount()));
//            notifyRepaymentDetailDTOList.add(notifyRepaymentDetailDTO);
//        }
        if (createDTO.getDefaultFine() == null) {
            createDTO.setDefaultFine(BigDecimal.valueOf(0L));
        }
        repaymentAmount=new BigDecimal(money);
        createDTO.setRepaymentAmount(repaymentAmount.add(createDTO.getDefaultFine()));//还款金额
        createDTO.setDetails(notifyRepaymentDetailDTOList);
        return apiSyncClient.createNotifyRepayment(createDTO);
    }


    public static List<InstallmentDTO> constructRepaymentScheduleDetails() {
        List<InstallmentDTO> list = new ArrayList();
        Calendar calendar = Calendar.getInstance();
        calendar.add(5, 10);

        for(int i = 1; i <= 12; ++i) {
            InstallmentDTO installment = new InstallmentDTO();
            installment.setInstallmentNo(i);
            installment.setInterestStartDate(DateFormatUtils.format(calendar, "yyyyMMdd"));
            calendar.add(2, 1);
            installment.setDueDate(DateFormatUtils.format(calendar, "yyyyMMdd"));
            installment.setDueAmount(BigDecimal.valueOf(120L));
            installment.setDuePrincipalAmount(BigDecimal.valueOf(100L));
            installment.setDueInterestAmount(BigDecimal.valueOf(20L));
            installment.setInterestEndDate(DateFormatUtils.format(calendar, "yyyyMMdd"));
            list.add(installment);
        }

        return list;
    }

    /**
     * 查询放款结果
     * @return
     */
    public static ResponseBean queryDisburseResult(String userId) {
        DisburseQueryDTO queryDTO = new DisburseQueryDTO();
        queryDTO.setTrafficIdentifier(TRAFFIC);
        queryDTO.setProductIdentifier(PRODUCT);
        USER_ID=userId;
        queryDTO.setUserId(USER_ID);
        queryDTO.setOrderId(genOrderId());
        return apiSyncClient.queryDisburseResult(queryDTO);
    }

    /**
     * 保存流量方用户信息（在实名认证成功后调用）
     * @return
     * @throws JsonProcessingException
     */
    public static ResponseBean createTrafficUser(TrafficUserDTO users) throws JsonProcessingException {
        TrafficUserDTO user = new TrafficUserDTO();
        user.setTrafficIdentifier(TRAFFIC);
        user.setProductIdentifier(PRODUCT);
        user.setUserId(users.getUserId());
        user.setIdType(IdType.ID_CARD.name());
//        user.setIdType("身份证");
        user.setIdNumber(users.getIdNumber());//身份证
        user.setName(users.getName());//用户姓名
        user.setMobileNumber(users.getMobileNumber());//手机号
        user.setGender(users.getGender());//性别
//        user.setTags(genTags());//标签
//        user.setContacts(constructContactList());//联系人集合
//        user.setExtraData(genExtraData());//其他信息
        return apiSyncClient.createTrafficUser(user);
    }
    /**
     * 更新流量方用户信息
     * @return
     */
    public static ResponseBean updateUserDetails() {
        TrafficUserDTO user = new TrafficUserDTO();
        user.setTrafficIdentifier(TRAFFIC);
        user.setUserId(USER_ID);
        user.setIdType(IdType.ID_CARD.name());
        user.setIdNumber(genIdNumber());
        user.setName(genUserName());
        user.setMobileNumber("13828380000");
        user.setEmail("test@email");
        user.setCompanyName("advance.ai");
        return apiSyncClient.updateTrafficUser(user);
    }

    /**
     * 更新流量方用户信息
     * @return
     */
    public static ResponseBean updateUserDetailsMore() {
        TrafficUserDTO user = new TrafficUserDTO();
        user.setTrafficIdentifier(TRAFFIC);
        user.setUserId(USER_ID);
        user.setIdType(IdType.ID_CARD.name());
        user.setIdNumber(genIdNumber());
        user.setName(genUserName());
        user.setMobileNumber("1382838");
        user.setCompanyName("advance.ai@beijing");
        user.setMonthlyIncome(BigDecimal.valueOf(1000L));
        return apiSyncClient.updateTrafficUser(user);
    }

    /**
     * 更新流量方用户信息
     * @return
     */
    public static ResponseBean updateUserContracts(TrafficUserDTO users,List<ContactDTO> contactDTOList) {
        TrafficUserDTO user = new TrafficUserDTO();
        user.setTrafficIdentifier(TRAFFIC);
        user.setProductIdentifier(PRODUCT);
        user.setUserId(users.getUserId());
        user.setIdType(IdType.ID_CARD.name());
        user.setIdNumber(users.getIdNumber());//身份证
        user.setName(users.getName());//用户姓名
        user.setMobileNumber(users.getMobileNumber());//手机号
        user.setGender(users.getGender());//性别
        user.setContacts(contactDTOList);
        return apiSyncClient.updateTrafficUser(user);
    }

    public static String genIdNumber() {
        return ID_NUMBER;
    }

    public static String genUserName() {
        return USER_ID;
    }

    public static String genOrderId() {
        return "JM-" + GenerateNum.getInstance().GenerateOrder();
    }

    public static String genMobileNumber() {
        return MOBILE_NUMBER;
    }

    public static String genExtraData() throws JsonProcessingException {
        Map<String, Object> map = new HashMap();
        map.put("orderTimes", 3);
        map.put("favorite", "music");
        return (new ObjectMapper()).writeValueAsString(map);
    }

    public static String genTags() throws JsonProcessingException {
        Map<String, Object> map = new HashMap();
        map.put("source", "JUMEI");
        map.put("level", "VIP3");
        return (new ObjectMapper()).writeValueAsString(map);
    }

    public static List<ContactDTO> constructContactList() {
        List<ContactDTO> list = new ArrayList();
        ContactDTO contact = new ContactDTO();
        contact.setContactName("大明");
//        contact.setContactIdNumber("111222333");
        contact.setContactMobileNumber("15288230000");
        contact.setIsEmergencyContact(true);
        contact.setRelation("父子");
        list.add(contact);
        contact = new ContactDTO();
        contact.setContactName("Fox");
        contact.setContactMobileNumber("15288230000");
        contact.setIsEmergencyContact(false);
        list.add(contact);
        return list;
    }

    /**
     * 保存预授信额度信息
     * @return
     * @throws JsonProcessingException
     */
    public static ResponseBean createCreditLinePrecheck(Map<String,String> map) throws JsonProcessingException {
        CreditLinePrecheckDTO creditLinePrecheckDTO = new CreditLinePrecheckDTO();
        creditLinePrecheckDTO.setTrafficIdentifier(TRAFFIC);
        creditLinePrecheckDTO.setProductIdentifier(PRODUCT);
        creditLinePrecheckDTO.setUserId(map.get("userId"));
        creditLinePrecheckDTO.setName(map.get("userName"));
        creditLinePrecheckDTO.setIdType(IdType.ID_CARD.name());
        creditLinePrecheckDTO.setIdNumber(map.get("idNumber"));
        creditLinePrecheckDTO.setContractAmount(BigDecimal.valueOf(Double.valueOf(map.get("contractAmount"))));//额度协议金额
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> platformData = new HashMap();
        creditLinePrecheckDTO.setPlatformData(objectMapper.writeValueAsString(platformData));
        Map<String, Object> thirdPartyData = new HashMap();
        creditLinePrecheckDTO.setThirdPartyData(objectMapper.writeValueAsString(thirdPartyData));
        return apiSyncClient.createCreditLinePrecheck(creditLinePrecheckDTO);
    }

    /**
     * 保存授信额度信息
     * @return
     */
    public static ResponseBean createCreditLine(Map<String,String> map) {
        Calendar calendar = Calendar.getInstance();
        CreditLineDTO creditLineDTO = new CreditLineDTO();
        creditLineDTO.setTrafficIdentifier(TRAFFIC);
        creditLineDTO.setProductIdentifier(PRODUCT);
        creditLineDTO.setContractNo(map.get("contractNo"));//授信额度协议编号
        creditLineDTO.setUserId(map.get("userId"));//用户id
        creditLineDTO.setName(map.get("name"));//借款人姓名
        creditLineDTO.setIdType(IdType.ID_CARD.name());//借款人证件类型
        creditLineDTO.setIdNumber(map.get("idNumber"));//借款人证件号码
        String curDate = DateFormatUtils.format(calendar, "yyyyMMdd");
        creditLineDTO.setContractSignDate(curDate);//额度协议签订日期
        creditLineDTO.setContractBeginDate(curDate);//额度协议起期
        calendar.add(1, 20);
        creditLineDTO.setContractEndDate(DateFormatUtils.format(calendar, "yyyyMMdd"));//额度协议止期
        creditLineDTO.setContractAmount(new BigDecimal(map.get("contractAmount")));//额度协议金额
        creditLineDTO.setUsedAmount(BigDecimal.valueOf(0L));//已用额度
        creditLineDTO.setRemainAmount(new BigDecimal(map.get("contractAmount")));//剩余额度
        creditLineDTO.setGuarantyType(GuarantyType.CREDIT.name());//担保方式
        creditLineDTO.setIsCircle(true);//是否循环额度
        creditLineDTO.setContractStatus(ContractStatus.EFFECTIVE.name());//协议状态
        return apiSyncClient.createCreditLine(creditLineDTO);
    }

    /**
     * 银行卡预授权申请
     * @return
     */
    public static ResponseBean requestBindCardAuthDemo(Map<String,String> map) {
        BindCardAuthRequestDTO requestDTO = new BindCardAuthRequestDTO();
        requestDTO.setTrafficIdentifier(TRAFFIC);
        requestDTO.setProductIdentifier(PRODUCT);
        requestDTO.setUserId(map.get("userId"));
        requestDTO.setBankAccountName(map.get("userName"));
        requestDTO.setBankCardNumber(map.get("backCardNumber"));
        requestDTO.setBankMobileNumber(map.get("mobileNumber"));
        requestDTO.setIdNumber(map.get("idNumber"));
        return apiSyncClient.requestBindCardAuth(requestDTO);
    }

    /**
     * 银行卡预授权确认
     * @param map
     * @return
     */
    public static ResponseBean confirmBindCardAuthDemo(Map<String,String> map) {
        BindCardAuthConfirmDTO confirmDTO = new BindCardAuthConfirmDTO();
        confirmDTO.setAuthProtocolNo(map.get("authProtocolNo"));
        confirmDTO.setCardAuthNo(map.get("cardAuthNo"));
        confirmDTO.setVerificationCode(map.get("verificationCode"));
        return apiSyncClient.confirmBindCardAuth(confirmDTO);
    }

    /**
     * 保存订单信息
     * @return
     */
    public static ResponseBean createOrder(Map<String,String>map) {
        Calendar calendar = Calendar.getInstance();
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setTrafficIdentifier(TRAFFIC);
        orderDTO.setProductIdentifier(PRODUCT);
        //OrderCoderUtil.toCode(Long.parseLong(map.get("userId")))
        orderDTO.setContractNo(map.get("contractNo"));//贷款合同编号
        orderDTO.setUserId(map.get("userId"));
        orderDTO.setOrderId(map.get("orderId"));//订单编号
        String curDate = DateFormatUtils.format(calendar, "yyyyMMdd");
        orderDTO.setContractSignDate(curDate);//合同签订日期
        orderDTO.setContractBeginDate(curDate);//合同有效起始日期
        calendar.add(1, 20);
        orderDTO.setContractEndDate(DateFormatUtils.format(calendar, "yyyyMMdd"));//合同有效结束日期
        orderDTO.setContractStatus(ContractStatus.EFFECTIVE.name());//合同状态
        orderDTO.setContractAmount(BigDecimal.valueOf(Double.parseDouble(map.get("contractAmount"))));//合同金额
        orderDTO.setLoanBalance(BigDecimal.valueOf(Double.valueOf(map.get("loanBalance"))));//贷款余额
        orderDTO.setApplyAmount(BigDecimal.valueOf(Double.parseDouble(map.get("trialAmount"))));//申请金额
        orderDTO.setLoanAmount(BigDecimal.valueOf(Double.parseDouble(map.get("trialAmount"))));//实际放款金额
        orderDTO.setLoanRate(BigDecimal.valueOf(0.02D));//贷款利率
        orderDTO.setRateType(RateType.MONTHLY.name());
        orderDTO.setOverdueFineRate(BigDecimal.valueOf(0.02D));//逾期罚息利率
        orderDTO.setTenor(Integer.valueOf(map.get("installments")));//贷款期限
        orderDTO.setTenorUnit(TenorUnit.MONTHS.name());//贷款期限计时单位
        orderDTO.setInstallments(Integer.valueOf(map.get("installments")));//总分期数
        orderDTO.setRepaymentMethod(RepaymentMethod.ACPI.name());//还款方式
        orderDTO.setBankAccountName(map.get("bankAccountName"));//银行账户名
        orderDTO.setBankCardNumber(map.get("bankCardNumber"));//银行卡号
        orderDTO.setBankName(map.get("bankName"));//银行名称
        orderDTO.setBankMobileNumber(map.get("bankMobileNumber"));//银行卡绑定的手机号
        orderDTO.setRepaymentBankAccountName(map.get("bankAccountName"));//还款银行账户名
        orderDTO.setRepaymentBankCardNumber(map.get("bankCardNumber"));//还款银行卡号
        orderDTO.setRepaymentBankName(map.get("bankName"));//还款银行名称
        orderDTO.setRepaymentBankMobileNumber(map.get("bankMobileNumber"));//还款银行卡绑定的手机号
        orderDTO.setReplaceAllOrderRepaymentBankCard(true);//是否以本次的还款银行卡替换该用户所有订单还款银行卡，默认为false
        orderDTO.setIdType(IdType.ID_CARD.name());//用户的证件类型
        orderDTO.setIdNumber(map.get("idNumber"));//用户的证件号码
        orderDTO.setExpectedRepaymentAmount(BigDecimal.valueOf(Double.parseDouble(map.get("contractAmount"))));//预计总还款金额
        orderDTO.setCreateAt(System.currentTimeMillis());
        return apiSyncClient.createOrder(orderDTO);
    }


    /**
     * 根据订单号查询订单信息
     * @param orderQueryDTO
     * @return
     */
    public static ResponseBean queryOrderResult(OrderQueryDTO orderQueryDTO) {
        orderQueryDTO.setTrafficIdentifier(TRAFFIC);
        orderQueryDTO.setProductIdentifier(PRODUCT);
        return apiSyncClient.queryOrderResult(orderQueryDTO);
    }

    /**
     * 根据订单号查询还款计划
     * @param repaymentScheduleQueryDTO
     * @return
     */
    public static ResponseBean queryRepaymentScheduleResult(RepaymentScheduleQueryDTO repaymentScheduleQueryDTO) {
        repaymentScheduleQueryDTO.setTrafficIdentifier(TRAFFIC);
        repaymentScheduleQueryDTO.setProductIdentifier(PRODUCT);
        return apiSyncClient.queryRepaymentScheduleResult(repaymentScheduleQueryDTO);
    }


    /**
     * 还款计划试算
     * @param map
     * @return
     */
    public static ResponseBean trailRepaymentSchedule(Map<String,Object> map) {
        RepaymentScheduleTrialDTO trialDTO=new RepaymentScheduleTrialDTO();
        trialDTO.setProductIdentifier(PRODUCT);
        trialDTO.setInstallments(Integer.parseInt(map.get("installments")+""));
        trialDTO.setLoanDate(DateUtils.getDate());
        trialDTO.setTrialAmount(BigDecimal.valueOf(Double.parseDouble(map.get("trialAmount")+"")));
        trialDTO.setBillDate(10);
        log.info("Calling trailRepaymentSchedule with productIdentifier {}", trialDTO.getProductIdentifier());
        return apiSyncClient.trailRepaymentSchedule(trialDTO);
    }
    /**
     * 贷款总金额（通过还款计划试算所以应还的总和）
     * @param map
     * @return
     */
    public static double trailRepaymentScheduleSum(Map<String,Object> map) {
        RepaymentScheduleTrialDTO trialDTO=new RepaymentScheduleTrialDTO();
        trialDTO.setProductIdentifier(PRODUCT);
        trialDTO.setInstallments(Integer.parseInt(map.get("installments")+""));
        trialDTO.setLoanDate(DateUtils.getDate());
        trialDTO.setTrialAmount(BigDecimal.valueOf(Double.parseDouble(map.get("trialAmount")+"")));
        trialDTO.setBillDate(10);
        log.info("Calling trailRepaymentSchedule with productIdentifier {}", trialDTO.getProductIdentifier());
        ResponseBean responseBean =apiSyncClient.trailRepaymentSchedule(trialDTO);
        double sumPrice=0.0;
        if(responseBean.getCode().equals("SUCCESS")){
            List<Map<String,Object>> mapList=(List<Map<String,Object>>)responseBean.getData();
            for (Map<String, Object> stringStringMap : mapList) {
                sumPrice+=Double.valueOf(stringStringMap.get("dueAmount")+"");
//            System.out.println(stringStringMap.get("dueAmount"));
            }
        }else{
            throw  new XException("第三方服务端错误");
        }
        return sumPrice;
    }




    /**
     * 用户额度查询
     * @param userId
     * @return
     */
    public static ResponseBean queryCreditLineResult(String userId) {
        CreditLineQueryDTO creditLineQueryDTO =new CreditLineQueryDTO();
        creditLineQueryDTO.setTrafficIdentifier(TRAFFIC);
        creditLineQueryDTO.setProductIdentifier(PRODUCT);
        creditLineQueryDTO.setUserId(userId);
        return apiSyncClient.queryCreditLineResult(creditLineQueryDTO);
    }


    /**
     * 查询预授信审核结果
     * @param userId
     * @return
     */
    public static ResponseBean queryCreditLinePrecheckResult(String userId) {
        CreditLinePrecheckSecondDecisionResultQueryDTO queryDTO=new CreditLinePrecheckSecondDecisionResultQueryDTO();
        queryDTO.setTrafficIdentifier(TRAFFIC);
        queryDTO.setProductIdentifier(PRODUCT);
        queryDTO.setUserId(userId);
        return apiSyncClient.queryCreditLinePrecheckResult(queryDTO);
    }


    /**
     * 授信结果查询
     * @param userId
     * @param contractNo
     * @return
     */
    public static ResponseBean queryCreditLineSecondDecisionResult(String userId,String contractNo) {
        CreditLineSecondDecisionResultQueryDTO queryDTO=new CreditLineSecondDecisionResultQueryDTO();
        queryDTO.setTrafficIdentifier(TRAFFIC);
        queryDTO.setProductIdentifier(PRODUCT);
        queryDTO.setUserId(userId);
        queryDTO.setCreditLineContractNo(contractNo);
        return apiSyncClient.queryCreditLineSecondDecisionResult(queryDTO);
    }

    static {
        ID_NUMBER = "110420198807" + USER_ID;
        MOBILE_NUMBER = "1387464" + ((new Random()).nextInt(9000) + 1000);
    }


    public static void main(String[] args) {
//        RepaymentScheduleQueryDTO repaymentScheduleQueryDTO=new RepaymentScheduleQueryDTO();
//        repaymentScheduleQueryDTO.setOrderId("TMH201810251751055860001");
//        repaymentScheduleQueryDTO.setUserId("40");
        OrderQueryDTO orderQueryDTO=new OrderQueryDTO();
        orderQueryDTO.setTrafficIdentifier(TRAFFIC);
        orderQueryDTO.setProductIdentifier(PRODUCT);
        orderQueryDTO.setUserId("62");
        orderQueryDTO.setOrderId("TMH201810292149156540001");
        System.out.println(BfUtil.queryOrderResult(orderQueryDTO));
    }
}
